package com.kee.server.manager.parser;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.jsoup.Jsoup;
import org.jsoup.helper.StringUtil;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.safety.Whitelist;
import org.jsoup.select.Elements;

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
import com.kee.server.dao.ExamDao;
import com.kee.server.dao.IExamDao;
import com.kee.share.bean.Exam;

public class Doc2Html {

	private final static String IMAGE_PRE_PATH = "http://static.kerxue.com/t/";
	
	private final static IExamDao examDao = new ExamDao();
	
	private final static Whitelist whitelist = new Whitelist();
	
	private final static String HTML_PATH = "J:/html/";
	
	private final static String TEMP_IMAGE_PATH = "J:/image/";
	
	static {
		whitelist.addTags("p");
		whitelist.addTags("span");
		whitelist.addTags("img");
		whitelist.addAttributes("img", "src");
		whitelist.addAttributes("span", "text-decoration");
		whitelist.addTags("table");
		whitelist.addTags("tr");
		whitelist.addTags("td");
	}
	
	/**
	 * word转html
	 * 
	 * @param docfile
	 * @param htmlfile
	 */
	public static void wordToHtml(String docfile, String htmlfile) {
		if(false){
		ActiveXComponent app = new ActiveXComponent("Word.Application"); // 启动word
		try {
			app.setProperty("Visible", new Variant(false));
			Dispatch docs = app.getProperty("Documents").toDispatch();
			Dispatch doc = Dispatch.invoke(
					docs,
					"Open",
					Dispatch.Method,
					new Object[] { docfile, new Variant(false),
							new Variant(true) }, new int[1]).toDispatch();
			Dispatch.invoke(doc, "SaveAs", Dispatch.Method, new Object[] {
					htmlfile, new Variant(8) }, new int[1]);
			Dispatch.call(doc, "Close", new Variant(false));
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			app.invoke("Quit", new Variant[] {});
		}
		}
	}

	/**
	 * 解释出html的题目
	 * @param html
	 * @return
	 */
	public static Map<String,String> parseExam(String html) {
		Map<String, String> map = new LinkedHashMap<String, String>();
		String h = Jsoup.parse(html).body().html().replaceAll("\n", "");
		for (int i = 1; i <= 40; i++) {
			String regx = "\\>(" + i + ")、(.*?)(?=(\\>(" + (i+1) + ")、))";
			Pattern pattern = Pattern.compile(regx);
			Matcher m = pattern.matcher(h);
			while (m.find()) {
				map.put(m.group(1), m.group(2) + ">");
			}
		}
		System.out.println("解析到试题题目  " + map.size() + " 道");
		return map;
	}

	/**
	 * 答案解析
	 * @param html
	 * @return
	 */
	public static Map<String,String> parseAnswer(String html) {
		Map<String, String> map = new LinkedHashMap<String, String>();
		String h = Jsoup.parse(html).body().html().replaceAll("\n", "");
		for (int i = 1; i <= 40; i++) {
			String regx = "\\>(" + i + ")\\.(.*?)(?=(\\>(" + (i+1) + ")\\.))";
			Pattern pattern = Pattern.compile(regx);
			Matcher m = pattern.matcher(h);
			while (m.find()) {
				map.put(m.group(1), m.group(2) + ">");
			}
		}
		System.out.println("解析到答案题目  " + map.size() + " 道");
		return map;
	}
	
	
	/**
	 * 将一个文件转换成文本
	 * @param filePath
	 * @return
	 * @throws IOException
	 */
	public static String file2String(String filePath) throws IOException{
		InputStreamReader reader = new InputStreamReader(new FileInputStream(
				filePath), "gbk");
		BufferedReader read = new BufferedReader(reader);
		StringBuilder builder = new StringBuilder();
		String str;
		while ((str = read.readLine()) != null) {
			builder.append(str);
			builder.append("\n");
		}
		return builder.toString();
	}
	
	
	
	public static String filter(String html) {
		// 去掉多余html
		DateFormat date = new SimpleDateFormat("yyyyMMdd");
		String fileIndex = date.format(new Date());
		String text = Jsoup.clean(html, whitelist);
		text = text.replaceAll("&#65533;", "");
		text = text.replaceAll("�", "");
		text = text.replaceAll("<span></span>", "");
		text = text.replaceAll("<p></p>", "");
		Document doc = Jsoup.parse(text);
		Elements imgElements = doc.select("img[src]");
		for (Element img : imgElements) {
			String src = img.attr("src");
			String name = UUID.randomUUID().toString().replaceAll("-", "");
			String ext = FilenameUtils.getExtension(src);
			String newFileName = name + "." + ext;
			String destSrc = IMAGE_PRE_PATH + fileIndex + "/" + newFileName;
			copyFile(HTML_PATH + src, TEMP_IMAGE_PATH + newFileName);
			img.attr("src", destSrc);
		}
		return Jsoup.clean(doc.html(), whitelist);
	}
	
	
	public static void copyFile(String src, String dest) {
		try {
			FileUtils.copyFile(new File(src), new File(dest));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 解析路径
	 * @param docPath 文件路径
	 * @param examDocFileName 不包括文件名后缀  统一为.docx格式
	 * @param analyDocFileName
	 * @param htmlPath
	 */
	public static void parse(String docPath,String examDocFileName,String analyDocFileName,String htmlPath){
		String examDocURL = docPath+examDocFileName+".docx";
		String examHtmlURl = htmlPath + examDocFileName+".html";
		wordToHtml(examDocURL, examHtmlURl);
		Map<String,String> examMap = null;
		String html;
		try {
			//doc 生成  html
			html = file2String(examHtmlURl);
			//对html生成 map(题号,题目)
			examMap = parseExam(html);
		} catch (IOException e) {
			e.printStackTrace();
		}
		String answerDocURL = docPath + analyDocFileName+".docx";
		String answerHtmlURL = htmlPath + analyDocFileName+".html";
		wordToHtml(answerDocURL, answerHtmlURL);
		Map<String,String> answerMap = null;
		try {
			String html1 = file2String(answerHtmlURL);
			answerMap = parseAnswer(html1);
		} catch (IOException e) {
			e.printStackTrace();
		}
		Set<String> set = examMap.keySet();
		Iterator<String> it = set.iterator();
		while(it.hasNext()){
			String key = it.next(); 
			String exam = examMap.get(key);
			String answer = answerMap.get(key);
			if (!StringUtil.isBlank(exam) && !StringUtil.isBlank(answer)) {
				Exam e = new Exam();
				String ex = filter(exam);
				System.out.println(ex);
				e.setExam(ex);
				e.setAnswer(filter(answer));
				e.setWebsite(3);
				e.setType(2);
				e.setOpts("");
				e.setGrade("");
				e.setSubject("数学");
				e.setKnowledge("实践与应用");
				try {
					examDao.add(e);
				} catch (SQLException e1) {
					e1.printStackTrace();
				}
			}
		}
	}
	
	public static void main(String[] args) throws IOException {

		String docPath = "F:/baiduyundownload/数学1-2.files/";
		// String htmlPath = "F:/baiduyundownload/数学1-2.files/";
		String docExamFileName = "数学1-2.html";
		String docAnaFileName = "数学1-2-1.html";
		parse(docPath, docExamFileName, docAnaFileName, HTML_PATH);
	}

}
